<template>
  <div id="doAnswerPage">
    <h1 class="title">{{ appVO?.appName }}</h1>
    <el-button type="warning" plain disabled v-if="loginUserStore.loginUser.userRole === UserRoleEnum.NOT_LOGIN">
      提示: 您当前处于未登录状态, 需要登录才能提交回答
    </el-button>

    <!-- 题目列表 -->
    <div class="questionListWrapper">
      <div v-for="(question, questionIndex) in questionList">
        <h2>{{ questionIndex + 1 }}. {{ question.title }}</h2>
        <el-radio-group v-model="answer.choices![questionIndex]">
          <el-radio v-for="(option) in question.options" :key="option.key" :value="option.key">
            {{ option.key }}. {{ option.value }}
          </el-radio>
        </el-radio-group>
      </div>
    </div>

    <el-button class="submitButton" type="primary" @click="doSubmit"
      :disabled="submitting || !allAnswered" :loading="submitting"
      v-if="loginUserStore.loginUser.userRole !== UserRoleEnum.NOT_LOGIN">
      提交答案并查看结果
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { getAppVoByIdUsingGet } from '@/api/appController';
import { listQuestionVoByPageUsingPost } from '@/api/questionController';
import { addUserAnswerUsingPost, generateUserAnswerIdUsingGet } from '@/api/userAnswerController';
import { ResponseCodeEnum, ScoringStrategyEnum, SqlSortOrderEnum, UserRoleEnum } from '@/enums';
import { ElLoading, ElMessage } from 'element-plus';
import { computed, onMounted, ref, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useLoginUserStore } from '@/stores/userStore';

const { appId } = defineProps(["appId"])
const router = useRouter();
const loginUserStore = useLoginUserStore();

// 应用 VO + 题目 VO + 题目列表
const appVO = ref<API.AppVO>();
const questionVO = ref<API.QuestionVO>();
const questionList = ref<API.QuestionContentDTO[]>([]);

// 回答 Request 结构
const answer = ref<API.UserAnswerAddRequest>({
  id: 0,
  appId,
  choices: [],
});

// 是否全部已回答
const allAnswered = computed(() => {
  return answer.value.choices?.every(item => item !== undefined);
});

onMounted(async () => {
  // 为题目列表添加加载效果
  const loading = ElLoading.service({
    target: ".questionListWrapper",
    lock: true,
    text: "加载中...",
  });

  // 获取应用信息
  const appResult = await getAppVoByIdUsingGet({
    id: appId
  });

  if (appResult.data.code === ResponseCodeEnum.SUCCESS && appResult.data.data) {
      appVO.value = appResult.data.data;
    } else {
      ElMessage.error("获取应用数据失败: " + appResult.data.message);
  }

  // 查询得到该应用的最新题目列表 (1 条记录)
  const questionResult = await listQuestionVoByPageUsingPost({
    appId,
    current: 1,
    pageSize: 1,
    sortField: "createTime",
    sortOrder: SqlSortOrderEnum.DESC,
  });

  // 尝试获取已有题目
  if (questionResult.data.code === ResponseCodeEnum.SUCCESS && questionResult.data.data?.records) {
    questionVO.value = questionResult.data.data?.records[0];
    // 因为当题目不存在时 records 是空数组, 所以这里要判断一下, 否则会报错
    if (questionVO.value) {
      questionList.value = questionVO.value.questionContent ?? [];
      // 将答案列表填充满 undefined
      answer.value.choices = new Array(questionList.value.length).fill(undefined);
    }
  } else {
    ElMessage.error("获取题目列表失败: " + questionResult.data.message);
  }

  // 获取结果 id (目的是当用户提交答案时, 数据库只会多一条数据, 不会因为重发请求而出现多条数据)
  const answerIdResult = await generateUserAnswerIdUsingGet();
  if (answerIdResult.data.code === ResponseCodeEnum.SUCCESS) {
    answer.value.id = answerIdResult.data.data;
  } else {
    ElMessage.error("获取唯一 id 失败: " + answerIdResult.data.message);
  }

  loading.close();
});

// 是否正在提交结果
const submitting = ref(false);

/**
 * 提交
 */
const doSubmit = async () => {
  submitting.value = true;

  if (appVO.value?.scoringStrategy === ScoringStrategyEnum.AI) {
    ElMessage.info("正在提交中... (由于是 AI 评分, 评分需要一定时间)")
  }
  const result = await addUserAnswerUsingPost(answer.value);

  if (result.data.code === ResponseCodeEnum.SUCCESS && result.data.data) {
    ElMessage.success("提交成功!");
    router.push({
      name: "答题结果",
      params: {
        id: result.data.data,
      }
    })
  } else {
    ElMessage.error("提交失败: " + result.data.message);
  }

  submitting.value = false;
}

</script>

<style scoped lang="less">
#doAnswerPage {
  padding: 20px;
  width: 50%;
  margin: 0 auto;

  .title {
    font-size: 3em;
    margin: 50px 0;
  }

  .submitButton {
    margin: 20px 0;
  }
}
</style>
